﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlServerCe;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Delta.Forms
{
    public partial class ViewDBTable : Form
    {
        private string ConnectionString;
        private string TableName;

        public ViewDBTable(string connectionString, string tableName)
        {
            InitializeComponent();
            ConnectionString = connectionString;
            TableName = tableName;
            this.Text = "Просмотр таблицы '" + TableName + "'";
            ViewTable();
        }

        /// <summary>
        /// Просмотр таблицы БД
        /// </summary>
        private void ViewTable()
        {
            dgvDBTable.Columns.Clear();
            string x = TableName;
            SqlCeConnection sqlCeConnection = new SqlCeConnection(ConnectionString);
            sqlCeConnection.Open();
            List<string[]> data = new List<string[]>();
            SqlCeCommand sqlCeCommand =
                new SqlCeCommand("SELECT [2] FROM __SysObjects WHERE ([1] = '" + x + "')",
                sqlCeConnection);
            SqlCeDataReader sqlCeDataReader = sqlCeCommand.ExecuteReader();
            List<object> li = new List<object>();
            while (sqlCeDataReader.Read())
            {
                int n = sqlCeDataReader.FieldCount;
                object[] objects = new object[1];
                sqlCeDataReader.GetValues(objects);
                dgvDBTable.Columns.Add(objects[0].ToString(), objects[0].ToString());
            }

            sqlCeCommand = new SqlCeCommand("SELECT * FROM [" + x + "]", sqlCeConnection);
            sqlCeDataReader = sqlCeCommand.ExecuteReader();
            while (sqlCeDataReader.Read())
            {
                int n = sqlCeDataReader.FieldCount;
                object[] objects = new object[n];
                sqlCeDataReader.GetValues(objects);
                dgvDBTable.Rows.Add(objects.Select(y => y.ToString()).ToArray());
            }
            sqlCeConnection.Close();
        }
    }
}